package com.xiyi.shouxin.dao.admin;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.xiyi.shouxin.dao.BaseRepository;
import com.xiyi.shouxin.dao.JdbcPreparedStatement;
import com.xiyi.shouxin.entity.admin.RoleMenuRef;
import com.xiyi.shouxin.entity.admin.mapper.RoleMenuRefMapper;
import com.xiyi.shouxin.exception.CommonException;
import com.xiyi.shouxin.exception.ErrorCode;

@Repository
public class RoleMenuRefRepository extends BaseRepository<RoleMenuRef> {
    public RoleMenuRefRepository() {
        super();
        super.stat = new JdbcPreparedStatement<>(RoleMenuRef.class);
    }

    public List<RoleMenuRef> findAllByRoleId(Long roleId) throws Exception {
        if (roleId == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        StringBuilder sb = new StringBuilder("SELECT ");
        sb.append(stat.GetQueryColumns());
        sb.append(" FROM ");
        sb.append(stat.GetTableName());
        sb.append(" WHERE ");
        sb.append(stat.GetColumnName("roleId"));
        sb.append(" = ? ");
        List<RoleMenuRef> list = template.query(sb.toString(), new RoleMenuRefMapper(), roleId);
        return list;
    }

    public List<RoleMenuRef> findAllByMenuId(Long menuId) throws Exception {
        if (menuId == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        StringBuilder sb = new StringBuilder("SELECT ");
        sb.append(stat.GetQueryColumns());
        sb.append(" FROM ");
        sb.append(stat.GetTableName());
        sb.append(" WHERE ");
        sb.append(stat.GetColumnName("menuId"));
        sb.append(" = ? ");
        List<RoleMenuRef> list = template.query(sb.toString(), new RoleMenuRefMapper(), menuId);
        return list;
    }

    public void delByMenuId(Long menuId) throws CommonException {
        if (menuId == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        StringBuilder sb = new StringBuilder("DELETE FROM ");
        sb.append(stat.GetTableName());
        sb.append(" WHERE ");
        sb.append(stat.GetColumnName("menuId"));
        sb.append(" = ? AND ");
        sb.append(stat.GetColumnName("id"));
        sb.append(" > 0");
        template.update(sb.toString(), menuId);
    }
}
